if(isWxBrowser() && !sessionStorage.getItem('openid')){
	location.href = "http://www.sharestock.cn/oauth2/wxMobileGet/authorize"
}

//时间格式化
Date.prototype.format = function(fmt) { //author: meizz 
    var o = {
        "Y+": this.getFullYear(), //完整年份
        "y+": this.getFullYear() % 100, //年份后2位 
        "m+": this.getMonth() + 1, //月份 
        "M+": this.getMonth() + 1, //月份
        "D+": this.getDate(), //日 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "h+": this.getHours(), //小时  
        "I+": this.getMinutes(), //分 
        "i+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "S+": this.getMilliseconds(), //毫秒
    };
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (((k == "Y+" ? "0000" : "00") + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

function genderShow(type) {
    switch (type) {
        case "MALE":
            return "男";
        case "FEMALE":
            return "男";
        default:
            return "未知";
    }
}

//判断是否登录
function isLogined(path) {
    if (!G.getCookie('jwt')) {
        location.href = '/m/login.html?from=' + path;
        alert('请登录');
        return;
    }
}

//免费下载提示登录
$(document).on('click', '.down-free', function(e) {
    var productId = $(this).data('id');
    if (!G.getCookie('jwt')) {
        location.href = '/m/login.html';
        alert('请登录');
        return;
    }
    if(isWxBrowser()){
    	alert('请在非微信浏览器上进行下载！')
    	return;
    }
    url = G.apiurl + 'api/product/' + productId + '/download?token=' + G.getCookie('jwt')
    var a = $('<a href="" download="download"></a>');
    a.attr('href', url);
    // alert(url)
    a[0].click()
})

//图片懒加载
$((function() {
    var lazyload = function() {
        var imgObjs = $("img[data-lazyload-img]");
        var el = [];
        var url = [];
        for (var i = 0; i < imgObjs.length; i++) {
            url[i] = $(imgObjs[i]).attr("data-lazyload-img");
            if (typeof url[i] == "string" && url[i].length > 0) {
                el[i] = new Image();
                el[i].setAttribute("data-id", i);
                el[i].onload = function() {
                    var i = $(this).attr("data-id");
                    var obj = $(imgObjs[i]);
                    obj.attr("src", obj.attr("data-lazyload-img")).removeAttr("data-lazyload-img");
                    el[i] = null;
                    url[i] = null;
                };
                el[i].onerror = function() {};
                el[i].src = url[i];
            }
        }
    };
    window.lazyload = lazyload;
})());

function formatOutline(outline) {
    return outline.replace(/\n/g, '<br>')
}

function formatVal(obj, defaultVal) {
    return obj ? obj : (defaultVal != undefined ? defaultVal : "-");
}

//加载
var loading = {
    open: function() {
        var div = document.createElement('div');
        div.className = 'loading-layer';
        div.style.width = '100%';
        div.style.height = '100%';
        div.style.backgroundColor = 'rgba(0,0,0,.5)';
        div.style.position = 'fixed';
        div.style.top = '0';
        div.style.left = '0';
        div.style.zIndex = '999';
        var img = document.createElement('img');
        img.className = 'loading-img';
        img.src = '/public/images/m/loading.gif';
        img.style.position = 'fixed';
        img.style.top = '50%';
        img.style.left = '50%';
        img.style.zIndex = '9999';
        img.style.marginLeft = '-18.5px';
        img.style.marginTop = '-18.5px';
        document.body.appendChild(div)
        document.body.appendChild(img)
        document.body.style.overflow = 'hidden'
    },
    close: function() {
        var el = document.querySelector('.loading-layer');
        var img = document.querySelector('.loading-img');
        document.body.removeChild(el)
        document.body.removeChild(img)
        document.body.style.overflow = 'auto'
    }
}

$(function() {
    var userId = G.getCookie('sdk_user_id')
    //头部
    var header = '<div class="new-header flex flex-center-box">\
            <img src="/public/images/m/logo.png" alt="" class="logo-icon-header">\
            <div class="right-icon-flex">\
                <a href="/m/user.html" class="right-header-href" id="J_user_center"><img src="/' + G.defaultAvator + '" data-lazyload-img="' + G.uploadurl + '/avator/' + userId + '.png" alt="" class="user-header-icon"></a>\
                <a href="/m/help.html" class="right-icon-href"><img src="/public/images/m/help.png" alt=""></a>\
            </div>\
        </div>';
    $('#header').html(header)
    //尾部
    var footer = '<div class="footer">\
            客服热线：028-61533448<br>四川省成都市锦江区一环路东五段108号<br>\
            版权所有：思多客网络科技有限公司<br>\
            蜀ICP备17029708号-1\
        </div>';
    $('#footer').html(footer)
    //导航
    var menus = [
        { url: "/m/index.html", title: '当日精选', socpe: ["/m/index.html", '/m/'] },
        { url: "/m/video.html", title: "节目访谈", socpe: ["/m/video.html"] },
        { url: "/m/filter.html", title: "回顾筛选", socpe: ["/m/filter.html"] },
        { url: "/m/master.html", title: "专家坐诊", socpe: ["/m/master.html"] },
        { url: "/m/reward.html", title: "悬赏发布", socpe: ["/m/reward.html"] }
    ];
    var html = "";
    var pathname = location.pathname;
    for (var i = 0; i < menus.length; i++) {
        var menu = menus[i];
        var addClass = menu.socpe.indexOf(pathname) !== -1;
        html += '<a class="flex-1 m-nav-item ' + (addClass ? "m-current-nav-item" : "") + '" href="' + menu.url + '">' + menu.title + '</a>'
    }
    $("#nav").html('<div class="row m-nav flex">' + html + '</div>');

    //添加jweixin.js到页面
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://res.wx.qq.com/open/js/jweixin-1.2.0.js';
    head.appendChild(script);
})
// $(document).on('click','#J_user_center',function(){
//     var src = location.pathname.slice(3)
//     isLogined(src)
// })
$('.back-box').click(function() {
    var key = G.getQuery('from');
    if (key == 'user.html') {
        location.href = '/m/index.html';
        return;
    }
    history.back()
})

$(document).on('click', '.download', function(e) {
	if (isWxBrowser()) {
        e.preventDefault();
        //微信浏览器提示浏览器打开
        alert('请在浏览器上进行操作!')
        return
	}
})

function isWxBrowser() {
    var ua = navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == "micromessenger";
}

function exit() {
    G.deleteCookie('jwt');
    G.deleteCookie('sdk_user_id');
    G.deleteCookie('sdk_user_type');
    G.deleteCookie('rewardId');
    G.deleteCookie('localUserId');
    alert('退出成功')
    location.href = "/m/login.html";
}


function onBridgeReady(e,callback) {
    // console.log(e)
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', e,
        function(res) {
            console.log(res)
            if (res.err_msg == "get_brand_wcpay_request:ok") {
            	if(callback){
            		callback()
            	}else{
	            	alert('支付成功，请在非微信浏览器中进行下载!')
            	}
            } // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
        }
    );
}



//微信内支付
function wxApppay(getBrandWCPayRequest,callback) {
	var s = "";
	for(var k in getBrandWCPayRequest) {
		s += k + "=" + getBrandWCPayRequest[k] + ";\n";
	}
	// alert(s);
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', function() {
                onBridgeReady(getBrandWCPayRequest,callback)
            }, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', function() {
                onBridgeReady(getBrandWCPayRequest,callback)
            });
            document.attachEvent('onWeixinJSBridgeReady', function() {
                onBridgeReady(getBrandWCPayRequest,callback)
            });
        }
    } else {
        onBridgeReady(getBrandWCPayRequest);
    }
}
// var callbackParams = {
//     "appId": "wx2421b1c4370ec43b", //公众号名称，由商户传入     
//     "timeStamp": "1395712654", //时间戳，自1970年以来的秒数     
//     "nonceStr": "e61463f8efa94090b1f366cccfbbb444", //随机串     
//     "package": "prepay_id=u802345jgfjsdfgsdg888",
//     "signType": "MD5", //微信签名方式：     
//     "paySign": "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
// }
// wxApppay(callbackParams) //ajax添加订单然后调用支付方法